const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const { codeInspectorPlugin } = require('code-inspector-plugin');
const isDev = process.env.NODE_ENV !== 'production';

/** @type {import('webpack').Configuration} */
module.exports = {
    entry: path.resolve(__dirname, 'src/index.tsx'),
    output: {
        path: path.resolve(__dirname, 'dist'),
        filename: 'bundle.[contenthash].js',
        clean: true,
        publicPath: '/',
    },
    resolve: {
        extensions: ['.ts', '.tsx', '.js', '.jsx'],
        alias: {
            '@': path.resolve(__dirname, 'src'),
        },
    },
    devServer: {
        static: {
            directory: path.join(__dirname, 'dist'),
        },
        port: 5173,
        hot: true,
        open: true,
        historyApiFallback: true,
    },
    module: {
        rules: [
            {
                test: /\.tsx?$/,
                use: 'ts-loader',
                exclude: /node_modules/,
            },
            {
                test: /\.css$/,
                use: ['style-loader', 'css-loader'],
            },
            // 支持 .less 普通样式
            {
                test: /\.less$/,
                exclude: /\.module\.less$/,
                use: [
                    'style-loader',
                    'css-loader',
                    {
                        loader: 'less-loader',
                        options: { lessOptions: { javascriptEnabled: true } },
                    },
                ],
            },
            // 支持 CSS Modules: *.module.less
            {
                test: /\.module\.less$/,
                use: [
                    'style-loader',
                    {
                        loader: 'css-loader',
                        options: { modules: { localIdentName: '__[local]_[hash:base64:10]' } },
                        // options: { modules: { localIdentName: isDev ? '[name]__[local]' : '[hash:base64:6]' } },
                    },
                    {
                        loader: 'less-loader',
                        options: { lessOptions: { javascriptEnabled: true } },
                    },
                ],
            },
        ],
    },
    plugins: [
        new HtmlWebpackPlugin({
            template: path.resolve(__dirname, 'public/index.html'),
            filename: 'index.html',
        }),
        // ...(isDev ? [codeInspectorPlugin({ bundler: 'webpack' })] : []),
    ],
};
